﻿<%@ WebHandler Language="C#" Class="RSLossReasonReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 燃烧废品原因分类统计报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.7.6
 **/

public class RSLossReasonReport : IHttpHandler
{
    public bool IsReusable { get { return false; } }
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT pf.productfamilyname,lr.lossreasonname,COUNT(DISTINCT csr.productid) qty 
FROM Checkqtychangerecord ch
LEFT JOIN
(
     SELECT pt.productfamilyname,cf.containerid  FROM containerproductfamilylist cf 
     LEFT JOIN productfamily pt ON pt.productfamilyid=cf.productfamilylistid
     WHERE cf.sequence=1
     GROUP BY pt.productfamilyname,cf.containerid
) pf ON pf.containerid=ch.containerid
LEFT JOIN LOSSREASON lr ON lr.lossreasonid=ch.reasonid
LEFT JOIN containersteprecord csr ON csr.containerid=ch.containerid
WHERE ch.isuse=0 AND ch.scrapsourcetype IN (1,2,3,4,5) AND ch.changeqtytype=2 
";
        //分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND csr.factoryid = '{0}'", jObject["factoryid"].ToString());
        }

        //检验日期
        if (jObject["checkdate"] != null && jObject["checkdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["checkdate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(csr.checkdate) BETWEEN TO_DATE('{0}','yyyy-mm-dd') and TO_DATE('{1}','yyyy-mm-dd')", arr[0].ToString(), arr[1].ToString());
            }
        }

        sql += " GROUP BY pf.productfamilyname,lr.lossreasonname";
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["productfamilyname"].Caption = "型别";
        dtResult.Columns["lossreasonname"].Caption = "代号";
        dtResult.Columns["qty"].Caption = "件数";
        ExportHelper.ExportExcel(dtResult, jObject["factoryname"].ToString() + "废品原因分类统计报表");
    }
}